import axios from 'axios'
import store from '@/store/index.js'
import router from '../router/auth.js'
// 创建axios的实例，配置
// 1. 基地址
const request = axios.create({
  // baseURL: 'http://toutiao-app.itheima.net'
  // baseURL: 'http://192.168.15.28:8000'

  baseURL: 'http://localhost:8000'

})

// 请求拦截器1
// config本次请求用到的配置
request.interceptors.request.use(function (config) {
  const token = store.state.tokenInfo.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})


// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    console.log('响应拦截器', response)
    return response
  }
  ,
  async function (error) {
    // 如果发生了错误，判断是否是401
    console.dir(error)
    if (error.response.status === 401) {
      // 开始处理
      console.log('响应拦截器-错误-401')
      const refreshToken = store.state.tokenInfo.refresh_token
      // if (有refresh_token) {
      if (refreshToken) {
        // 1. 请求新token
        try {
          const res = await axios({
            url: 'http://localhost:8000/v1_0/authorizations',
            method: 'PUT',
            headers: {
              Authorization: `Bearer ${refreshToken}`
            }
          })
          console.log('请求新token', res.data.data.token)
          // 2. 保存到vuex
          store.commit('msetToken', {
            refresh_token: refreshToken,
            token: res.data.data.token
          })
          // 3. 重发请求
          //    request是上面创建的axios的实例，它会自动从vuex取出token带上
          return request(error.config)
        } catch (error) {
          // 清除token
          store.commit('msetToken', {})
          // 去到登录页(如果有token值，就不能到login)
          const backtoUrl = encodeURIComponent(router.currentRoute.fullPath)
          router.push('/login?backto=' + backtoUrl)
          return Promise.reject(error)
        }
      } else {
        // 去到登录页
        // 清除token
        store.commit('msetToken', {})
        const backtoUrl = encodeURIComponent(router.currentRoute.fullPath)
        router.push('/login?backto=' + backtoUrl)
        return Promise.reject(error)
      }
    } else {
      return Promise.reject(error)
    }
  })




export const request2 = axios.create({
  baseURL: 'http://toutiao-app.itheima2.net2'
})

// 导出
export default request
